    <?php

class Application_Model_Mesa extends Zend_Db_Table_Abstract {

    protected $_name = 'mesa';
    protected $_primary = 'idmesa';
    private static $instance;
    protected $_schema = 'pub';

    public static function getInstance() {
        if (!isset(self::$instance)) {
            self::$instance = new Application_Model_Mesa();
            return self::$instance;
        }
        return self::$instance;
    }

    public function insert($data) {
        if (isset($data['lugares']) && isset($data['observacoes']) && isset($data['reservada'])){
            parent::insert($data);
        }
    }

    public function update(array $data, $where = '') {
        $where = 'idmesa = ' . $data['idmesa'];
        parent::update($data, $where);
    }

    public function getById($id) {
        return $this->fetchRow("idmesa = " . $id);
    }

    public function getAll(){
        $sql = 'select * from '.$this->_schema.'.'.$this->_name;
        return $this->getAdapter()->fetchAll($sql);
    }

    public function getList(){
        $sql = 'select idmesa,lugares from '.$this->_schema.'.'.$this->_name;
        return $this->getAdapter()->fetchAll($sql);
    }
    
    public function getMesasReserva($date){
        $sql= "select m.*,
                    case(select
                         count(*)
                         from reservas r
                         where r.data = '".$date."'
                         and r.mesa = m.idmesa
                        )
                     
                    when 0 then 'N'
                    else'S' end as res,
                    COALESCE((select
                         distinct  r.hora
                        from reservas r
                        where r.data = '".$date."'
                        and r.mesa = m.idmesa
                        and r.hora_saida is null
                      ),'S/R') as hora
                 from mesa m
                  order by res";
        return $this->getAdapter()->fetchAll($sql);
    }
    
    
    public function remove($id){
        $where = ' idmesa = ' .$id;
        parent::delete($where);
    }
    
    
}